package test.stubs;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import messages.BaseMessage;
import messages.GeneralAck;
import messages.MessageFactory;
import messages.MessageType;
import messages.registration.ObserverRegistrationMessage;

public class ObserverStub {
    
    private Socket remoteSock;
    
    public boolean connect(int port) throws IOException
    {
        remoteSock = new Socket(InetAddress.getLocalHost(), port);
        
        remoteSock.getOutputStream().write(new ObserverRegistrationMessage().toByteArray());
        
        BaseMessage mess = MessageFactory.readMessage(remoteSock);
        
        if (mess.getMessageType() != MessageType.GeneralAck)
        {
            remoteSock.close();
            return false;
        }
        
        GeneralAck ack = (GeneralAck) mess;
        if ( ack.getAckMessageType() != MessageType.ObserverRegistrationMessage || !ack.getSuccess())
        {
            remoteSock.close();
            return false;
        }
        
        return true;
    }
    
    public BaseMessage readObserver() throws IOException
    {
        return MessageFactory.readMessage(remoteSock);
    }
    
    public void close() throws IOException
    {
        remoteSock.close();
    }
    
}
